//
//  LSLTableViewController.m
//  LSL_IJKPlayer
//
//  Created by 大龙 on 18/1/8.
//  Copyright © 2018年 LSL. All rights reserved.
//

#import "LSLTableViewController.h"
#import "LSLTableViewCell.h"

@interface LSLTableViewController ()

@end

@implementation LSLTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.urlArray = @[@"http://flv2.bn.netease.com/videolib3/1603/09/OoUpN9394/SD/OoUpN9394-mobile.mp4",
                      @"http://flv2.bn.netease.com/videolib3/1603/09/WGLTN7350/SD/WGLTN7350-mobile.mp4",
                      @"http://flv2.bn.netease.com/videolib3/1603/09/yIfqn6818/SD/yIfqn6818-mobile.mp4",
                      @"http://flv2.bn.netease.com/videolib3/1603/09/aWLiT6526/SD/aWLiT6526-mobile.mp4",
                      @"http://flv2.bn.netease.com/videolib3/1603/09/ZsmaY5784/SD/ZsmaY5784-mobile.mp4",
                      @"http://flv2.bn.netease.com/videolib3/1603/09/FtQxN5386/SD/FtQxN5386-mobile.mp4",
                      @"http://flv2.bn.netease.com/videolib3/1603/09/nxHyl5135/SD/nxHyl5135-mobile.mp4",
                      @"http://flv2.bn.netease.com/videolib3/1603/09/DifSb5073/SD/DifSb5073-mobile.mp4",
                      @"http://flv2.bn.netease.com/videolib3/1603/09/FdwZS6751/SD/FdwZS6751-mobile.mp4",
                      @"http://flv2.bn.netease.com/videolib3/1603/09/ZquUJ6596/SD/ZquUJ6596-mobile.mp4"];
                      
                      
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Incomplete implementation, return the number of sections
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete implementation, return the number of rows
    return 10;
}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 200;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellID = @"cellID";
    
    LSLTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [[LSLTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    __weak LSLTableViewCell *weakcell = cell;
    __weak typeof(self) weakSelf = self;
    cell.playBlock = ^{
        weakSelf.playerView = [LSLPlayerView sharePlayerView];
        weakSelf.playerView.delegate = weakSelf;
        
         NSURL * url = [NSURL URLWithString:weakSelf.urlArray[indexPath.row]];
        [weakSelf.playerView setVideoURL:url AtIndexPath:indexPath];
        [weakcell addSubview:weakSelf.playerView];
        [weakSelf.playerView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(weakcell.mas_top);
            make.bottom.equalTo(weakcell.mas_bottom).with.offset(-20);
            make.left.equalTo(weakcell.mas_left);
            make.right.equalTo(weakcell.mas_right);
        }];
        
        [weakSelf addTableViewObserver];//添加观察者
        
        
    };
    if (indexPath.row == 0) {
        cell.backgroundColor = [UIColor blueColor];
    }else{
        cell.backgroundColor = [UIColor redColor];
    }
    
    // Configure the cell...
    
    return cell;
}

/**
 *  添加Tableview观察者
 */
- (void)addTableViewObserver {
    if (self.tableView) {
        // 监听tab偏移量
        [self.tableView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:nil];
    }
}
/**
 *  移除TableView观察者
 */
- (void)removeTableViewObserver {
    if (self.tableView) {
        [self.tableView removeObserver:self forKeyPath:@"contentOffset"];
    }
}

#pragma mark ---- KVO监听播放器是否在屏幕内 ----
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    if ([keyPath isEqualToString:@"contentOffset" ]) {
        [self handleCellWithPlayerViewInTableViewWithDict:change];
    }
}

-(void)  handleCellWithPlayerViewInTableViewWithDict:(NSDictionary *)dict{
    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:self.playerView.indexPath];
    NSArray *visableCells =self.tableView.visibleCells;
    if ([visableCells containsObject:cell]) {
        
        return;
    }else {
        //在底部
        [self hidePlayerViewInTableView];
    }

    
}

- (void)hidePlayerViewInTableView{
    [self removeTableViewObserver];
    [self.playerView resetPlayer];
    [self.playerView removeFromSuperview];
    
    
    
}


#pragma mark ---- PlayerViewDelegate ----
- (void)returnPlayViewOnCellWithIndexPath:(NSIndexPath *)indexPath{
//    [_playerView removeFromSuperview];
    LSLTableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    [cell addSubview:_playerView];
    [_playerView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(cell.mas_top);
        make.bottom.equalTo(cell.mas_bottom).with.offset(-20);
        make.left.equalTo(cell.mas_left);
        make.right.equalTo(cell.mas_right);
    }];

}



/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
